package br.ufc.apsoo.interceptor;

import java.util.Arrays;

import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.ufc.apsoo.annotation.NaoInterceptavel;
import br.ufc.apsoo.controllers.LoginController;
import br.ufc.apsoo.controllers.ReservaController;
import br.ufc.apsoo.session.UsuarioSession;

@Intercepts
public class LoginInterceptor implements Interceptor {

	private Result result;
	private UsuarioSession usuarioSession;

	public LoginInterceptor(Result result, UsuarioSession usuarioSession) {
		this.result = result;
		this.usuarioSession = usuarioSession;
	}

	@Override
	public boolean accepts(ResourceMethod method) {
		return !Arrays.asList(LoginController.class).contains(
				method.getMethod().getDeclaringClass())
				&& !method.getMethod().isAnnotationPresent(NaoInterceptavel.class);
	}

	@Override
	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object resourceInstance) {
		if (usuarioSession.getUsuario() != null) {
			stack.next(method, resourceInstance);
		} else {
			result.redirectTo(LoginController.class).login();
		}
	}

}
